package com.example.autopia.view.Adapters

import android.util.Log
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.example.autopia.R
import com.example.autopia.databinding.ViewholderChannelItemBinding
import com.example.autopia.model.Item.User
import com.example.autopia.utilities.ImageManager
import com.example.autopia.view.Listeners.ChannelsListener
import com.example.autopia.view.Listeners.HotNewsListener

class ChannelsAdapter  :
    RecyclerView.Adapter<ChannelsAdapter.ViewHolder>() {

    private lateinit var list : MutableList<User>
   private lateinit var listener: ChannelsListener// Новый листенер
    private val imageManager = ImageManager()

    fun attachListener(listener: ChannelsListener) {
        this.listener = listener
    }
    fun setData(newList : List<User>){
        list = newList.toMutableList()
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val binding = ViewholderChannelItemBinding.inflate(
            LayoutInflater.from(parent.context),
            parent,
            false
        )
        return ViewHolder(binding)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val news = list[position]
        holder.bind(news,listener)
    }

    override fun getItemCount(): Int {
        return list.size
    }

    inner class ViewHolder(private val binding: ViewholderChannelItemBinding) :
        RecyclerView.ViewHolder(binding.root) {
        fun bind(user: User,listener: ChannelsListener) {
            binding.apply {

                Log.d("Yatoro",user.yourNewsList.toString())
                if (user.verificated != 0 ){
                    binding.ivVerificated.setImageResource(R.drawable.icon_verificated)
                }else{
                    binding.ivVerificated.setImageResource(R.drawable.icon_empty)
                }

                Glide.with(itemView)
                    .load(imageManager.byteArrayToBitmap(user.photo))
                    .centerCrop()
                    .placeholder(R.drawable.logo_placeholder)
                    .error(R.drawable.logo_placeholder)
                    .into(ivLogo)

                if (user.likesNewsList!=null){
                    tvCount.text = user.likesNewsList.size.toString()+" понравившихся обсуждений"
                }else{
                    tvCount.text = "0 обсуждений"
                }
                root.setOnClickListener {
                    listener.onChannelClick(user.id)
                }
                tvName.text = user.name

            }
        }
    }
}